package com.lk.controller;


import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
public class DownloadController {

//    @Value("${imgPath}")
    private String imgPath;


    @PostMapping("/upload")
    public Map<String, String> uploadImage(@RequestParam("file") MultipartFile file) {
        Path rootLocation = Paths.get(imgPath);
        Map<String, String> map = new HashMap<>();
        try {

            if (file.isEmpty()) {
                map.put("code", "10001");
                map.put("msg", "文件为空");
                return map;
            }
            String newName = UUID.randomUUID() + "_" + file.getOriginalFilename();
            Path destinationFile = rootLocation.resolve(Paths.get(newName))
                    .normalize().toAbsolutePath();
            if (!destinationFile.getParent().equals(rootLocation.toAbsolutePath())) {
                map.put("code", "10001");
                map.put("msg", "文件上传目录不存在");
                return map;
            }

            Files.copy(file.getInputStream(), destinationFile);
            map.put("code", "0");
            map.put("msg", "上传成功");

            map.put("name", newName);
            return map;
        } catch (IOException e) {
            map.put("code", "10003");
            map.put("msg", "上传失败" + e.getMessage());
            return map;
        }
    }

    @GetMapping("/showImg/{id}")
    public ResponseEntity<Resource> showImage(@PathVariable String id) {
        Path rootLocation = Paths.get(imgPath);

        Path file = rootLocation.resolve(id).normalize();
        Resource resource = null;
        try {
            resource = new UrlResource(file.toUri());
        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        }

        if (resource.exists() || resource.isReadable()) {
            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + resource.getFilename() + "\"")
                    .contentType(MediaType.IMAGE_JPEG)
                    .body(resource);
        } else {
            return ResponseEntity.notFound().build();

        }
    }
}